var guidePageID=sessionStorage.getItem("guidePageID")
var dataarr=""

    queryImg()
    function queryImg() {
    var datas={}
        if(guidePageID!="引导页"){
            datas={
                "id":guidePageID,
            }
        }else {
            datas={
                "pictureType":1
            }
        }
        $.ajax({
            type: "POST",
            url: root.appversioncontrol.readAppScreenMsg,
            cache: false,  //禁用缓存
            dataType: "json",
            async:false,//优先运行
            contentType: "application/json",
            data: JSON.stringify(datas),
            success: function (data) {
                var pitureUrlarr=[]
                dataarr=data.data
                if(data.data!="" && data.data!=null){
                    $("#ids").val(data.data[0].id)
                    var pitureUrls=data.data[0].pitureUrl.split(',')
                    var imglist2=""
                    for(var i=0; i<pitureUrls.length; i++){
                        imglist2+='<span class="guide_imgsrc replacePicture">'+
                            '<div class="updata_cot ">'+
                            '<input type="file" name="file" style="display: none"  onchange="putDataToPage(event,this,2)"  class="imgfile fileUpone" accept=".jpg,.jpeg,.gif,.png">'+
                            '<img class="fullPath"  style=" width: 140px;height: 198px;position: absolute;margin: -85px -56px;"  src="'+pitureUrls[i]+'" alt="" onclick="pictureUpload(this)">'+
                            '</div>'+
                            '<div class="ref_imgfilebox " >'+
                            '<input type="file" name="file" style="display: none"  onchange="updataDataToPage(event,this)"  class="imgfile fileUpone" accept=".jpg,.jpeg,.gif,.png">'+
                            '<span class="refsh_img chdelt_img" onclick="updataimgs(this)">修改</span>'+
                            '<span class="deletimg chdelt_img ml-10" onclick="deleteimgs(this)">删除</span>'+
                            '</div>'+
                            '</span>'

                    }
                    $("#oneimg").before(imglist2)
                }

                //默认图展示
                if($("#pictureDrag").find(".guide_imgsrc").length==11){

                    $("#oneimg").css({
                        display: "none"
                    });
                }else {
                    $("#oneimg").css({
                        display: "inline-block"
                    });
                }
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }

//图片上传
function pictureUpload(cen) {
    $(cen).prev().trigger('click');
}

// 上传图片返现
var heightsa=[]
var heightall={}
var upFileList = [] ;
function putDataToPage(e,can,type) {
    heightsa=[]
    //验证
    if(type==1){
        if($("#pictureDrag").find(".guide_imgsrc").length+e.target.files.length>11){
            layer.msg("引导图不可超过10张", {icon: 5,time:2000});
            $(".fileUpone").attr('type','text');
            $(".fileUpone").attr('type','file');
            return false;
        }
    }
    verificationPicFileType(can)
    verificationPicFileSize(can)
    upFileList = [] ;
    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        //实例化FileReader API
        upFileList.push(file) ;
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var img = new Image();
            img.src= data;
            img.onload = function(){
                var width = img.width;
                var height = img.height;
                //储存高度宽度
                heightall={
                    width1:width,
                    height1:height
                }
                var ppp={
                    "imgs":heightall
                }
                heightsa.push(ppp)
                if(type==2){
                    getupfilerul3(can,e)
                }else {
                    getupfilerul2(can,e)
                }

            };

        }
    }


}
// 多张提交上传图片
function getupfilerul2(can,e){
    var formData = new FormData();
    if(heightsa.length==upFileList.length){
        for (var s=0;s<heightsa.length;s++){
            if(heightsa[s].imgs.width1!=Number(750)&&heightsa[s].imgs.height1!=Number(1334)){
                $.Huimodalalert('图片要求750px*1334px，请重新上传',2000);
                $(".fileUpone").attr('type','text');
                $(".fileUpone").attr('type','file');
                return false;
            }
        }
    }else {
        return false;
    }

    for (var i=0;i<upFileList.length;i++){

        formData.append('file',upFileList[i]);
    }
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            //默认图隐藏
            //渲染上传多张的图片
            var imglist=""
            for(var i=0; i<data.length; i++){
                imglist+='<span class="guide_imgsrc replacePicture">'+
                    '<div class="updata_cot ">'+
                    '<input type="file" name="file" style="display: none"  onchange="putDataToPage(event,this,2)"  class="imgfile fileUpone" accept=".jpg,.jpeg,.gif,.png">'+
                    '<img class="fullPath"  style=" width: 140px;height: 198px;position: absolute;margin: -85px -56px;"  src="'+data[i].fullPath+'" alt="" onclick="pictureUpload(this)">'+
                    '</div>'+
                    '<div class="ref_imgfilebox " >'+
                    '<input type="file" name="file" style="display: none"  onchange="updataDataToPage(event,this)"  class="imgfile fileUpone" accept=".jpg,.jpeg,.gif,.png">'+
                    '<span class="refsh_img chdelt_img" onclick="updataimgs(this)">修改</span>'+
                    '<span class="deletimg chdelt_img ml-10" onclick="deleteimgs(this)">删除</span>'+
                    '</div>'+
                    '</span>'
            }
            //找过10张判断
            if($("#pictureDrag").find(".guide_imgsrc").length+data.length>11){
                $(".fileUpone").attr('type','text');
                $(".fileUpone").attr('type','file');
            }else {
                $("#oneimg").before(imglist)
            }
            //默认图展示
            if($("#pictureDrag").find(".guide_imgsrc").length==11){

                $("#oneimg").css({
                    display: "none"
                });
            }else {
                $("#oneimg").css({
                    display: "inline-block"
                });
            }
            replacePicture()
            addimgall()
        }
    })
}
//单张提交上传图片（满10张之后）
function getupfilerul3(can,e){
    var formData = new FormData();
    for (var i=0;i<upFileList.length;i++){
        formData.append('file',upFileList[i]);
    }
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            var imgsrc=$(can).parent().children()[1]
            $(imgsrc).attr("src",data[0].fullPath)
        }
    })
}

//修改图片
function updataimgs(cen) {
    $(cen).prev().trigger('click');
}

// 修改上传图片返现
function updataDataToPage(e,can) {
    //验证
    verificationPicFileType(can)
    verificationPicFileSize(can)
    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        //实例化FileReader API

        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var img = new Image();
            img.src= data;
            img.onload = function(){
                var width = img.width;
                var height = img.height;
                if (Number(width) == Number(750) && Number(height) == Number(1334)){
                    getupfilerul6(can,e)

                }else {
                    $.Huimodalalert('图片要求750px*1334px，请重新上传',2000);
                    file.value = "";
                    $(".fileUpone").attr('type','text');
                    $(".fileUpone").attr('type','file');
                    return;
                }
            };
        }
    }
}
// 提交上传图片
function getupfilerul6(can,e){
    var formData = new FormData();
    formData.append('file',$(can)[0].files[0]);
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            var imgsrc=$(can).parent().prev().children()[1]
            $(imgsrc).attr("src",data[0].fullPath)
        }
    })
}
var deletawei=''
//删除图片
function deleteimgs(can) {
    deletawei=can
    $("#deleteimg").css({
        display: "inline"
    });

  /*  var imgsrc=$(can).parent().prev().children()[1]
    $(imgsrc).attr("src","../../../img/imgs.png")*/
}
//确认取消
function confirmdelete() {
    $(deletawei).parent().parent().remove()
    //默认图隐藏展示
    if($("#pictureDrag").find(".guide_imgsrc").length==11){

        $("#oneimg").css({
            display: "none"
        });
    }else {
        $("#oneimg").css({
            display: "inline-block"
        });
    }
    $("#deleteimg").css({
        display: "none"
    });
    addimgall()
}
//取消删除
function canceldeleta(){
    $("#deleteimg").css({
        display: "none"
    });
}
//替换图片
replacePicture()
function replacePicture() {
    var div = $(".replacePicture")
    var container = null; // 存放拖拽元素的容器
    for (let i = 0; i < div.length; i++) {
        // 开始拖拽时把元素用容器存放
        div[i].ondragstart = function () {
            container = this;
        }
        // 默认当我dragover的时候会阻止我做drop操作，这里取消默认事件
        div[i].ondragover = function (e) {
            e.preventDefault()
        }
        // 当拖动结束的时候，给拖动的div所在位置的下面的div做drop事件
        div[i].ondrop = function () {
            if (container != null && container != this) {
                let temp = document.createElement('span')
                document.body.children[1].children[0].children[0].children[0].children[1].replaceChild(temp, this)
                document.body.children[1].children[0].children[0].children[0].children[1].replaceChild(this, container)
                document.body.children[1].children[0].children[0].children[0].children[1].replaceChild(container, temp)
            }
        }
    }
}
//保存图片
function preservationImg() {
    var  pictureDrags=$("#pictureDrag").find(".guide_imgsrc")
    var appScreenManage=[]
    var appScreenManages={}
    var urls=""
    if(guidePageID!="引导页"){
        urls=root.appversioncontrol.updateScreenMsg
        var imgall = "";//图片

        for (var k=0;k<pictureDrags.length;k++) {
            if($(pictureDrags[k]).find(".fullPath").attr("src")!="../../../img/imgs.png"){
                imgall +=  $(pictureDrags[k]).find(".fullPath").attr("src")+ ",";
            }


        }
        //去掉最后一个逗号(如果不需要去掉，就不用写)
        if (imgall.length > 0) {
            imgall = imgall.substr(0, imgall.length - 1);
        }

            appScreenManages={
                "id":guidePageID,
                "pictureName":"",//图片名称
                "pictureType":"1",//页面类型 1.引导页2.启动页3.广告页
                "pitureUrl":imgall,//图片url
                "platformType":"",//平台类型 10:签约平台 20:普通平台
                "areaCode":"",//区域code
                "placeType":"",//插入链接类型
                "placeContent":"",//插入链接内容
                "isSalesCustomer":"",//是否是经销商
                "isCountdown":"",//是否倒计时
                "isValidTime":"",//是否开启生效时间
                "startTime":"",
                "endTime":"",
                "detailContent":"",
                "updateUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,

        }
        appScreenManage.push(appScreenManages)
    }else {
        //引导页管理有数据时调用编辑接口无数据时调用新增
        if(dataarr=="" ||dataarr==null){
            urls=root.appversioncontrol.addScreenMsg

            var imgall = "";//图片

            for (var i=0;i<pictureDrags.length;i++) {
                if($(pictureDrags[i]).find(".fullPath").attr("src")!="../../../img/imgs.png"){
                    imgall +=  $(pictureDrags[i]).find(".fullPath").attr("src")+ ",";
                }


            }
            //去掉最后一个逗号(如果不需要去掉，就不用写)
            if (imgall.length > 0) {
                imgall = imgall.substr(0, imgall.length - 1);
            }
            appScreenManages={
                "pictureName":"",//图片名称
                "pictureType":"1",//页面类型 1.引导页2.启动页3.广告页
                "pitureUrl":imgall,//图片url
                "platformType":"",//平台类型 10:签约平台 20:普通平台
                "areaCode":"",//区域code
                "placeType":"",//插入链接类型
                "placeContent":"",//插入链接内容
                "isSalesCustomer":"",//是否是经销商
                "isCountdown":"",//是否倒计时
                "isValidTime":"",//是否开启生效时间
                "startTime":"",
                "endTime":"",
                "detailContent":"",
                "updateUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,

            }
            appScreenManage.push(appScreenManages)
        }else {

            urls=root.appversioncontrol.updateScreenMsg
            var imgall = "";//图片

            for (var k=0;k<pictureDrags.length;k++) {
                if($(pictureDrags[k]).find(".fullPath").attr("src")!="../../../img/imgs.png"){
                    imgall +=  $(pictureDrags[k]).find(".fullPath").attr("src")+ ",";
                }
            }
            //去掉最后一个逗号(如果不需要去掉，就不用写)
            if (imgall.length > 0) {
                imgall = imgall.substr(0, imgall.length - 1);
            }
            appScreenManages={
                "id":$("#ids").val(),
                "pictureName":"",//图片名称
                "pictureType":"1",//页面类型 1.引导页2.启动页3.广告页
                "pitureUrl":imgall,//图片url
                "platformType":"",//平台类型 10:签约平台 20:普通平台
                "areaCode":"",//区域code
                "placeType":"",//插入链接类型
                "placeContent":"",//插入链接内容
                "isSalesCustomer":"",//是否是经销商
                "isCountdown":"",//是否倒计时
                "isValidTime":"",//是否开启生效时间
                "startTime":"",
                "endTime":"",
                "detailContent":"",
                "updateUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,

            }
            appScreenManage.push(appScreenManages)
        }

    }
    $.ajax({
        type: "POST",
        url: urls,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({
            "appScreenManage":appScreenManage,
        }),
        success: function (data) {
            if(data.errorCode==0){
                layer.msg("保存成功",{icon: 6,time:2000},function () {
                    if(guidePageID!="引导页") {
                        setTimeout(function () {
                            window.parent.queryopenScreen(parent.comPageNum);
                            cancelLayerNoRefreshFn();
                        })
                    }else {
                        setTimeout(function () {
                            window.parent.queryopenScreen(parent.comPageNum);
                            cancelLayerNoRefreshFn(1);
                        })
                    }
                });
            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//取消
function cancelImg() {
    var cu = layer.confirm('<span>确认取消吗？</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
        parent.layer.closeAll();
        layer.close(cu);
    },function(){
        layer.close(cu);

    });

}
//保存按钮置灰
addimgall()
function addimgall() {
    if($("#pictureDrag").find(".guide_imgsrc").length==1){
        $("#addimgall").attr("style","background: darkgray;")
        $("#addimgall").removeAttr("onclick","preservationImg()")
    }else {
        $("#addimgall").attr("style","background: 3E84E9;")
        $("#addimgall").attr("onclick","preservationImg()")
    }

}
// 图片类型验证
function verificationPicFileType(file) {
    var flag=false;
    var fileTypes = [".jpg", ".jpeg",".gif",".png"];
    var filePath = file.value;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if(filePath){
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                flag= true;
                break;
            }
        }
        if (!isNext){
            $.Huimodalalert('格式仅支持jpg 、jpeg 、gif 、png',2000);
            file.value = "";
            flag=false;
        }
    }
    return flag;
}
//图片大小验证
function verificationPicFileSize(file) {
    var flag=false;
    var fileSize = 0;
    var fileMaxSize = 300;
    var filePath = file.value;
    if(filePath){
        fileSize =file.files[0].size;
        var size = fileMaxSize * Number(1024);
        if (fileSize > size) {
            $.Huimodalalert('图片大小超出300KB',2000);
            file.value = "";
            flag=false;
        }else{
            flag=true;
        }
    }
    return flag;
}